/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ejemplo;

/**
 *
 * @author samimikel
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import imagenes.ImageOps;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ByteLookupTable;
import java.awt.image.ColorModel;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.awt.image.LookupOp;
import java.awt.image.PixelGrabber;
import java.awt.image.RescaleOp;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

/**
 * 
 * @author samimikel
 */
public class utilidades {

	// static neuralNetwork n = null;
	private static long minutoTranscurrido;
	private static long segundoTranscurrido;
	private static long inicioTiempo;
	private static long horaTranscurrido;
//	public static neuralNetworkbak nn = new neuralNetworkbak();

//	static public String[] cargaFicheroPatrones(String fichero)
//			throws FileNotFoundException, IOException {
//
//		String[] pt = null;
//
//		fichero = "/Volumes/programacion/redneuronal/patrones/" + fichero;
//
//		File archivo = null;
//		FileReader fr = null;
//		BufferedReader br = null;
//
//		try {
//			// Apertura del fichero y creacion de BufferedReader para poder
//			// hacer una lectura comoda (disponer del metodo readLine()).
//			archivo = new File(fichero);
//			fr = new FileReader(archivo);
//			br = new BufferedReader(fr);
//
//			String l = "";
//
//			l = br.readLine();
//
//			// fr.close();
//
//			// Lectura del fichero*/
//			String linea = "";
//
//			String s = "";
//
//			s = l + ":";
//			while ((linea = br.readLine()) != null) {
//				s = s + linea + ":";
//			}
//
//			pt = s.split(":");
//			// System.out.println("dfd");
//			// pt=p;
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			// En el finally cerramos el fichero, para asegurarnos
//			// que se cierra tanto si todo va bien como si salta
//			// una excepcion.
//			try {
//				if (null != fr) {
//					fr.close();
//				}
//			} catch (Exception e2) {
//				e2.printStackTrace();
//			}
//		}
//
//		// ordenaArray(pt);
//
//		/*
//		 * for (int i=1;i<pt.length;i++){
//		 * 
//		 * guardaPatron("patronbak.txt", pt[i]); }
//		 */
//
//		return pt;
//
//	}

	static public String[] ordenaArray(String[] array) {
		Arrays.sort(array);
		return (array);
	}

	static public String[] cargaFicheroASCII() {

		String[] pt = null;

		pt = new String[63];

		pt[0] = "0000000";
		pt[1] = "1000001";
		pt[2] = "2000010";
		pt[3] = "3000011";
		pt[4] = "4000100";
		pt[5] = "5000101";
		pt[6] = "6000110";
		pt[7] = "7000111";
		pt[8] = "8001000";
		pt[9] = "9001001";
		pt[10] = "a001010";
		pt[11] = "b001011";
		pt[12] = "c001100";
		pt[13] = "d001101";
		pt[14] = "e001110";
		pt[14] = "f001111";
		pt[15] = "g010000";
		pt[16] = "h010001";
		pt[17] = "i010010";
		pt[18] = "j010011";
		pt[19] = "k010100";
		pt[20] = "l010101";
		pt[21] = "m010110";
		pt[22] = "n010111";
		pt[23] = "o011000";
		pt[24] = "p011001";
		pt[25] = "q011010";
		pt[26] = "r011011";
		pt[27] = "s011100";
		pt[28] = "t011101";
		pt[29] = "u011110";
		pt[30] = "v011111";
		pt[31] = "w100000";
		pt[32] = "x100001";
		pt[33] = "y100010";
		pt[34] = "z100011";
		pt[35] = "A100100";
		pt[36] = "B100101";
		pt[37] = "C100110";
		pt[38] = "D100111";
		pt[39] = "E101000";
		pt[40] = "F101001";
		pt[41] = "G101010";
		pt[42] = "H101011";
		pt[43] = "I101100";
		pt[44] = "J101101";
		pt[45] = "K101110";
		pt[46] = "L101111";
		pt[47] = "M110000";
		pt[48] = "N110001";
		pt[49] = "O110010";
		pt[50] = "P110011";
		pt[51] = "Q110100";
		pt[52] = "R110101";
		pt[53] = "S110110";
		pt[54] = "T110111";
		pt[55] = "U111000";
		pt[56] = "V111001";
		pt[57] = "W111010";
		pt[58] = "X111011";
		pt[59] = "Y111100";
		pt[60] = "Z111101";
		pt[61] = "?111110";
		pt[62] = "?111111";

		return pt;

	}

//	static public String isPatternValid(String p) {
//
//		String pp[] = new String[0];
//		String resultado = "";
//
//		int indice1 = nn.getNeuronasEntrada() * 2;
//		int indice2 = nn.getNeuronasSalida() * 2;
//
//		pp = nn.pattern.getPatrones();
//		
//		if (pp != null && pp.length > 0 && !pp.equals("null")) {
//
//			Arrays.sort(pp);
//			
//			for (int x = 0; x < pp.length; x++) {
//				
//				if (!pp[x].equals("null") && pp[x] != null) {
//					
//					//System.out.println("IGUALES "+pp[x]);
//					
//					if (p.equals(pp[x])){
//						resultado = "1";
//					}
//					 else {
//						String p1 = p.substring(0,  indice1);
//						String p2 = pp[x].substring(0, indice1);
//
//						if (p1.equals(p2)) {
//							resultado = "2"; 
//						}
//					}
//
//				}
//			}
//
//		}
//		if ( resultado=="") {
//			pp=insertElement(pp,p,pp.length);
//			nn.pattern.setPatrones(pp);
//		}
//		
//		return resultado;
//	}

	public static String[] insertElement(String original[], String element,
			int index) {
		int length = original.length;
		String destination[] = new String[length + 1];
		System.arraycopy(original, 0, destination, 0, index);
		destination[index] = element;
		System.arraycopy(original, index, destination, index + 1, length
				- index);
		return destination;
	}

	public static String bin2ascii(String bin) {

		String p[] = new String[65];

		String caracter = "";

		p = cargaFicheroASCII();

		for (int i = 1; i < p.length; i++) {

			// System.out.println(p[i].indexOf(bin));

			if (p[i].indexOf(bin) > 0) {
				caracter = p[i].substring(0, 1);
				break;
			}

		}

		return (caracter);
	}

	public static String ascii2bin(String ascii) {

		String p[] = new String[65];

		String caracter = "";

		p = cargaFicheroASCII();

		for (int i = 1; i < p.length; i++) {

			if (p[i].indexOf(ascii) >= 0) {

				String c = p[i];

				for (int j = 1; j < c.length(); j++) {

					caracter = caracter + c.charAt(j) + ";";
					// System.out.println(caracter);
				}

				break;
			}

		}

		return (caracter);
	}

//	public static void guardaPatron(String nombrefichero, String patron) {
//
//		// Validamos si existe el fichero
//		String sFichero = "/Volumes/programacion/redneuronal/patrones/"
//				+ nombrefichero;
//		try {
//			BufferedWriter bw = new BufferedWriter(new FileWriter(sFichero,
//					true));
//
//			bw.write(patron + "\n");
//
//			// Hay que cerrar el fichero
//			bw.close();
//		} catch (IOException ioe) {
//			ioe.printStackTrace();
//		}
//
//	}

	static public long getMinutoTranscurrido() {
		return minutoTranscurrido;
	}

	static public long getHoraTranscurrido() {
		return horaTranscurrido;
	}

	static public long getSegundoTranscurrido() {
		return segundoTranscurrido;
	}

	static public long initTime() {
		return inicioTiempo;
	}

	static public void resetTime() {
		inicioTiempo = System.currentTimeMillis();
		minutoTranscurrido = 0;
		segundoTranscurrido = 0;
		horaTranscurrido = 0;

	}

	static public void setTiempoTranscurrido() {

		long finalTiempo = System.currentTimeMillis();

		long milisegundos = (finalTiempo - initTime());
		long hora, minuto, segundo;
		long restohora, restominuto;

		hora = milisegundos / 3600000;
		restohora = milisegundos % 3600000;

		minuto = restohora / 60000;
		restominuto = restohora % 60000;

		segundo = restominuto / 1000;
		horaTranscurrido = hora;
		minutoTranscurrido = minuto;
		segundoTranscurrido = segundo;

	}

	public static boolean salvarImagen(final BufferedImage imagen,
			final String rutaFichero, final String formato) {

		// Comprobacion de parametros
		if (imagen != null && rutaFichero != null && formato != null) {

			try {
				ImageIO.write(imagen, formato, new File(rutaFichero));
				return true;
			} catch (Exception e) {
				// Fallo al guardar

				return false;
			}
		} else {
			// Fallo en los parametros
			return false;
		}
	}

	/*public static BufferedImage toBufferedImage(Image image) {
		*//** miramos uqe la imagen no sea ya una instancia de BufferedImage *//*
		if (image instanceof BufferedImage) {
			*//** genial, no hay que hacer nada *//*
			return ((BufferedImage) image);
		} else {
			*//** nos aseguramos que la imagen está totalmente cargada *//*
			image = new ImageIcon(image).getImage();
			*//** creamos la nueva imagen *//*

			BufferedImage bufferedImage = new BufferedImage(image
					.getWidth(null), image.getHeight(null),
					BufferedImage.TYPE_USHORT_GRAY);
			Graphics g = bufferedImage.createGraphics();
			g.drawImage(image, 0, 0, null);
			g.dispose();
			return (bufferedImage);
		}
	}*/
	
	
	// This method returns a buffered image with the contents of an image
	public static BufferedImage toBufferedImage(Image image) {
	    if (image instanceof BufferedImage) {
	        return (BufferedImage)image;
	    }

	    // This code ensures that all the pixels in the image are loaded
	    image = new ImageIcon(image).getImage();

	    // Determine if the image has transparent pixels; for this method's
	    // implementation, see Determining If an Image Has Transparent Pixels
	    boolean hasAlpha = hasAlpha(image);

	    // Create a buffered image with a format that's compatible with the screen
	    BufferedImage bimage = null;
	    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
	    try {
	        // Determine the type of transparency of the new buffered image
	        int transparency = Transparency.OPAQUE;
	        if (hasAlpha) {
	            transparency = Transparency.BITMASK;
	        }

	        // Create the buffered image
	        GraphicsDevice gs = ge.getDefaultScreenDevice();
	        GraphicsConfiguration gc = gs.getDefaultConfiguration();
	        bimage = gc.createCompatibleImage(
	            image.getWidth(null), image.getHeight(null), transparency);
	    } catch (HeadlessException e) {
	        // The system does not have a screen
	    }

	    if (bimage == null) {
	        // Create a buffered image using the default color model
	        int type = BufferedImage.TYPE_INT_RGB;
	        if (hasAlpha) {
	            type = BufferedImage.TYPE_INT_ARGB;
	        }
	        bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
	    }

	    // Copy image to buffered image
	    Graphics g = bimage.createGraphics();

	    // Paint the image onto the buffered image
	    g.drawImage(image, 0, 0, null);
	    g.dispose();

	    return bimage;
	}
	
	// This method returns true if the specified image has transparent pixels
	public static boolean hasAlpha(Image image) {
	    // If buffered image, the color model is readily available
	    if (image instanceof BufferedImage) {
	        BufferedImage bimage = (BufferedImage)image;
	        return bimage.getColorModel().hasAlpha();
	    }

	    // Use a pixel grabber to retrieve the image's color model;
	    // grabbing a single pixel is usually sufficient
	     PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
	    try {
	        pg.grabPixels();
	    } catch (InterruptedException e) {
	    }

	    // Get the image's color model
	    ColorModel cm = pg.getColorModel();
	    return cm.hasAlpha();
	}

	public static BufferedImage binariza(Image im) {
		
		BufferedImage reticula = toBufferedImage(im);

		int argb, r, b, g;
		String s = "";
		int colorBlanco=0;
		int colorNegro=0;
		int t = reticula.getWidth()*reticula.getWidth();
		
		for (int x = 0; x < reticula.getWidth(); x = x + 1) {
			for (int y = 0; y < reticula.getHeight(); y = y + 1) {

				argb = reticula.getRGB(x, y);
				r = 0xff & (argb >> 16);
				g = 0xff & (argb >> 8);
				b = 0xff & argb;

				int z = r + g + b;

				if (z > 700) {
					Color color1 = new Color(255, 255, 255);
					reticula.setRGB(x, y, color1.getRGB());
					
					colorBlanco++;
				} else {
					
					colorNegro++;
					Color color2 = new Color(0, 0, 0);
					reticula.setRGB(x, y, color2.getRGB());
				}
			}
			// s=s+"\n";
		}
		
		return reticula;

	}

	static boolean isGreyscaleImage(PixelGrabber pg) {
		return pg.getPixels() instanceof byte[];
	}

	public static int[] colorPromedio(Image im) {
		BufferedImage reticula = toBufferedImage(im);
		int sumatoriaR = 0;
		int sumatoriaG = 0;
		int sumatoriaB = 0;
		int[] promedio = new int[3];
		int argb, r, b, g;
		for (int x = 0; x < reticula.getWidth(); x = x + 1) {
			for (int y = 0; y < reticula.getHeight(); y = y + 1) {
				argb = reticula.getRGB(x, y);
				r = 0xff & (argb >> 16);
				g = 0xff & (argb >> 8);
				b = 0xff & argb;
				sumatoriaR += r;
				sumatoriaG += g;
				sumatoriaB += b;
			}
		}
		promedio[0] = Math.round(sumatoriaR
				/ (reticula.getWidth() * reticula.getHeight()));
		promedio[1] = Math.round(sumatoriaG
				/ (reticula.getWidth() * reticula.getHeight()));
		promedio[2] = Math.round(sumatoriaB
				/ (reticula.getWidth() * reticula.getHeight()));
		return promedio;
	}

	// public static BufferedImage toBufferedImage(Image image) {
	// if (image instanceof BufferedImage) {
	// return (BufferedImage)image;
	// }
	//    
	// // This code ensures that all the pixels in the image are loaded
	// image = new ImageIcon(image).getImage();
	//    
	// // Determine if the image has transparent pixels; for this method's
	// // implementation, see e661 Determining If an Image Has Transparent
	// Pixels
	// boolean hasAlpha = hasAlpha(image);
	//    
	// // Create a buffered image with a format that's compatible with the
	// screen
	// BufferedImage bimage = null;
	// GraphicsEnvironment ge =
	// GraphicsEnvironment.getLocalGraphicsEnvironment();
	// try {
	// // Determine the type of transparency of the new buffered image
	// int transparency = Transparency.OPAQUE;
	// if (hasAlpha) {
	// transparency = Transparency.BITMASK;
	// }
	//    
	// // Create the buffered image
	// GraphicsDevice gs = ge.getDefaultScreenDevice();
	// GraphicsConfiguration gc = gs.getDefaultConfiguration();
	// bimage = gc.createCompatibleImage(
	// image.getWidth(null), image.getHeight(null), transparency);
	// } catch (HeadlessException e) {
	// // The system does not have a screen
	// }
	//    
	// if (bimage == null) {
	// // Create a buffered image using the default color model
	// int type = BufferedImage.TYPE_INT_RGB;
	// if (hasAlpha) {
	// type = BufferedImage.TYPE_INT_ARGB;
	// }
	// bimage = new BufferedImage(image.getWidth(null), image.getHeight(null),
	// type);
	// }
	//    
	// // Copy image to buffered image
	// Graphics g = bimage.createGraphics();
	//    
	// // Paint the image onto the buffered image
	// g.drawImage(image, 0, 0, null);
	// g.dispose();
	//    
	// return bimage;
	// }

/*	public static boolean hasAlpha(Image image) {
		// If buffered image, the color model is readily available
		if (image instanceof BufferedImage) {
			return ((BufferedImage) image).getColorModel().hasAlpha();
		}

		// Use a pixel grabber to retrieve the image's color model;
		// grabbing a single pixel is usually sufficient
		PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
		try {
			pg.grabPixels();
		} catch (InterruptedException e) {
			System.out.println("no tiene alfa: " + e.getMessage());
		}
		// Get the image's color model
		return pg.getColorModel().hasAlpha();
	}*/
}
